<template>
  <div>
    <el-button type="primary" @click="showAddDialog">新增商品</el-button>
    <el-input v-model="searchQuery" @input="updateSearchQuery" placeholder="请输入商品名进行查询" style="margin-bottom: 20px; width: 500px;margin-left: 500px;"></el-input>
    <!--分页-->
    <el-pagination
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="filteredTableData.length"
      :current-page.sync="currentPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <!--表格内容-->
    <el-table
      ref="list"
      :data="paginatedTableData"
      style="width: 100%"
      border
      stripe
      highlight-current-row
      :default-sort="{prop: 'date', order: 'descending'}"
      @row-click="handleRowClick"
      @select-all="handleCheckedAllAndCheckedNone"
      @select="handleCheckedAllAndCheckedNone">
      <el-table-column
        type="selection"
        width="45"
        align="center">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        property="date"
        label="商品保质期"
        width="180"
        sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{scope.row.date}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="商品"
        width="180">
      </el-table-column>
      <el-table-column
        property="address"
        label="供货商">
      </el-table-column>
      <el-table-column
        property="price"
        label="价格(元)">
      </el-table-column>
      <el-table-column
        property="inventory"
        label="库存">
      </el-table-column>
      <el-table-column
        label="操作"
        width="130"
        align="center">
        <template slot-scope="scope">
          <el-button circle icon="el-icon-edit-outline" type="primary" title="编辑" size="small"
            @click="rowEdit(scope.$index, scope.row)"></el-button>
          <el-button circle icon="el-icon-delete" type="danger" title="删除" size="small"
            @click="rowDel(scope.$index, scope.row, $event);"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--编辑-弹出层-->
    <el-dialog
      title="编辑"
      :visible.sync="isShowEditDialog"
      width="500px"
      @close="dialogClose">
      <el-form
        ref="editForm"
        :model="formFileds"
        label-width="100px"
        :rules="rules">
        <el-form-item label="商品保质期">
          <el-date-picker v-model="formFileds.date" value-format="yyyy-MM-dd" :editable="false" :clearable="false"></el-date-picker>
        </el-form-item>
        <el-form-item label="商品" prop="name">
          <el-input v-model="formFileds.name"></el-input>
        </el-form-item>
        <el-form-item label="供货商" prop="address">
          <el-input v-model="formFileds.address"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="formFileds.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input v-model="formFileds.inventory"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleEdit(formFileds.id)" class="pull-right margin-l-25">确定</el-button>
          <el-button @click="isShowEditDialog = false;" class="pull-right">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="新增商品"
      :visible.sync="isShowAddDialog"
      width="500px"
      @close="dialogClose">
      <el-form
        ref="addForm"
        :model="addFormFields"
        label-width="100px"
        :rules="rules">
        <el-form-item label="商品保质期" prop="date">
          <el-date-picker v-model="addFormFields.date" value-format="yyyy-MM-dd" :editable="false" :clearable="false"></el-date-picker>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="addFormFields.name"></el-input>
        </el-form-item>
        <el-form-item label="供货商" prop="address">
          <el-input v-model="addFormFields.address"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="addFormFields.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input v-model="addFormFields.inventory"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">确定</el-button>
          <el-button @click="dialogClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';

export default {
  name: "sTable",
  data() {
    return {
      formFileds: {
        date: '',
        name: '',
        address: '',
        id: '',
        inventory: '',
        price: '',
      },
      addFormFields: {
        date: '',
        name: '',
        address: '',
        id: '',
        inventory: '',
        price: '', // 修正遗漏的字段
      },
      rules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '供货商不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ],
        inventory: [
          { required: true, message: '库存不能为空', trigger: 'blur' }
        ]
      },
      isShowEditDialog: false,
      isShowAddDialog: false
    }
  },
  computed: {
    ...mapState(['pageSize', 'currentPage', 'tableData', 'searchQuery']),
    ...mapGetters(['filteredTableData', 'paginatedTableData']),
  },
  methods: {
    ...mapMutations(['SET_PAGE_SIZE', 'SET_CURRENT_PAGE', 'SET_SEARCH_QUERY']),
    ...mapActions(['addItem', 'updateItem', 'deleteItem']),
    handleRowClick(row, event, column) {
      this.setCurRowChecked(row);
    },
    handleCheckedAllAndCheckedNone(selection) {
      1 != selection.length && this.$refs.list.setCurrentRow();
    },
    dialogClose() {
      this.$refs.editForm && this.$refs.editForm.resetFields();
      this.formFileds = {
        date: '',
        name: '',
        address: '',
        id: '',
        inventory: '',
        price: '',
      };
      this.isShowEditDialog = false;
      this.$refs.addForm && this.$refs.addForm.resetFields();
      this.isShowAddDialog = false;
    },
    rowEdit(index, row) {
      this.setCurRowChecked(row);
      this.formFileds = { ...row };  // 深拷贝数据对象
      this.isShowEditDialog = true;
    },
    handleEdit(id) {
      this.$refs.editForm.validate(isValid => {
        if (!isValid) return;
        this.updateItem({ ...this.formFileds });  // 深拷贝以确保数据一致性
        this.isShowEditDialog = false;
        this.$refs.list.sort('date', 'descending');
        this.$message.success('编辑成功');
      });
    },
    rowDel(index, row, event) {
      event.target.blur();
      this.$confirm('确定要下架当前商品吗？', '下架', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.deleteItem(row.id);
        this.$message.success('下架成功');
      }).catch(() => { });
    },
    setCurRowChecked(row) {
      this.$refs.list.clearSelection();
      this.$refs.list.toggleRowSelection(row);
    },
    showAddDialog() {
      this.isShowAddDialog = true;
    },
    handleAdd() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return;
        const newId = this.tableData.length + 1;
        this.addItem({
          id: newId,
          date: this.addFormFields.date,
          name: this.addFormFields.name,
          address: this.addFormFields.address,
          price: this.addFormFields.price,
          inventory: this.addFormFields.inventory,
        });
        this.dialogClose();
        this.$message.success('新增商品成功');
      });
    },
    dialogClose() {
      this.$refs.addForm && this.$refs.addForm.resetFields();
      this.isShowAddDialog = false;
    },
    handleCurrentChange(val) {
      this.SET_CURRENT_PAGE(val);
    },
    handleSizeChange(val) {
      this.SET_PAGE_SIZE(val);
      this.SET_CURRENT_PAGE(1);
    },
    updateSearchQuery(val) {
      this.SET_SEARCH_QUERY(val);
    }
  }
}
</script>

<style scoped lang="less">
.el-form {
  padding: 0 10px;
}
.el-date-editor {
  width: 100% !important;
}
</style>
